package com.daxt.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.Document;
import opennlp.tools.util.StringUtil;
//import com.aspose.pdf.Document;


public class WaterMarkUtil {
	private static int interval = -5;


	/**
	 * 多个水印
	 *
	 */
	public static void waterMark(String inputFile, String outputFile, String waterMarkName,BaseColor markBaseColor,String waterMarkSize) {
		try {

//            int begin = 1;
//            int end = 5;
//
//            FileInputStream file = new FileInputStream(inputFile);//创建流文件，其中inputFile是你的PDF文档路径
//            Document document = new Document();
//            PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputFile)); //输出pdf文件;
//            document.open();
//
//
//            byte[] b= new byte[file.available()]; ///这里是解决问题的重点
//            int len=0;
//            while((len=file.read(b))>0){
//
//                file.read(b,0,b.length);///这里是解决问题的重点
//
//                PdfReader pdfr=new PdfReader(new PdfReader(b));///这里是解决问题的重点
//
//                int num=pdfr.getNumberOfPages();
//                System.out.println("第一次页数是:"+num);
//                if(num<end||begin<0||begin>end){
//                    System.out.println("截取的页数不正确!");
//                }else {
//                    for(int i=begin;i<=end;i++){
//                        document.newPage();
//                        PdfImportedPage page=copy.getImportedPage(pdfr, i);
//                        copy.addPage(page);
//                    }
//                }
//            }
//            document.close();


//            FileInputStream file = new FileInputStream(inputFile);//创建流文件，其中inputFile是你的PDF文档路径
//            byte[] b=  new byte[file.available()];//获取字节
//            if(file.read(b)>0){
//                file.read(b,0,b.length);//将字节读入到文件里
//            }
//            PdfReader reader = null;// iText一个类
//            reader = new PdfReader(new PdfReader(b));

			PdfReader reader = new PdfReader(inputFile);
			PdfReader.unethicalreading = true;
			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			Rectangle pageRect = null;
			PdfGState gs = new PdfGState();
			gs.setFillOpacity(0.4f);
			gs.setStrokeOpacity(0.6f);
			int total = reader.getNumberOfPages() + 1;

			JLabel label = new JLabel();
			FontMetrics metrics;
			int textH = 0;
			int textW = 0;
			label.setText(waterMarkName);
			metrics = label.getFontMetrics(label.getFont());
			textH = metrics.getHeight();
			textW = metrics.stringWidth(label.getText());

			PdfContentByte under;

			int fontSize=20;
			if(!StringUtil.isEmpty(waterMarkSize)){
				fontSize=Integer.parseInt(waterMarkSize);
			}
			for (int i = 1; i < total; i++) {
				pageRect = reader.getPageSizeWithRotation(i);
				under = stamper.getOverContent(i);
				under.saveState();
				under.setGState(gs);
				under.beginText();
				under.setFontAndSize(base, fontSize);
				under.setColorFill(markBaseColor);
//				under.setColorFill(new BaseColor(192,192,192));
				for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 14) {
					for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 1) {
						under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 60);
					}
				}
				under.endText();
			}

			stamper.close();
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



//	/**
//	 * @description: 一个水印
//	 *
//	 * @author: lig
//	 * @date: 2021/7/23
//	 */
//	public static void waterMarkOne(String inputFile, String outputFile, String waterMarkName) {
//		try {
//			PdfReader reader = new PdfReader(inputFile);
//			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
//			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//			Rectangle pageRect = null;
//			PdfGState gs = new PdfGState();
//			gs.setFillOpacity(0.3f);
//			gs.setStrokeOpacity(0.4f);
//			int total = reader.getNumberOfPages() + 1;
//
//			JLabel label = new JLabel();
//			FontMetrics metrics;
//			int textH = 0;
//			int textW = 0;
//			label.setText(waterMarkName);
//			metrics = label.getFontMetrics(label.getFont());
//			textH = metrics.getHeight();
//			textW = metrics.stringWidth(label.getText());
//
//			PdfContentByte under;
//			for (int i = 1; i < total; i++) {
//				pageRect = reader.getPageSizeWithRotation(i);
//				under = stamper.getOverContent(i);
//				under.saveState();
//				under.setGState(gs);
//				under.beginText();
//				under.setFontAndSize(base, 80);
//				under.setColorFill(new BaseColor(192,192,192));
//
//
//				float h =  pageRect.getHeight()/2;
//				float w =  pageRect.getWidth()/2;
//				under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, w, h , 35);
//				under.endText();
//			}
//
//			stamper.close();
//			reader.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//	}







    /**
     * 图片添加水印
     *
     * @param srcImgPath
     *            需要添加水印的图片的路径
     * @param outImgPath
     *            添加水印后图片输出路径
     * @param markContentColor
     *            水印文字的颜色
     * @param waterMarkContent
     *            水印的文字
     */
    public static void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            // Font font = new Font("Courier New", Font.PLAIN, 12);
            Font font = new Font("宋体", Font.PLAIN, 20);
            g.setColor(markContentColor); // 根据图片的背景设置水印颜色

            g.setFont(font);

            /*int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
            int y = srcImgHeight - 3;
            // int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
            // int y = srcImgHeight / 2;
            g.drawString(waterMarkContent, x, y);*/


			Integer degree = -45;//设置水印文字的旋转角度
			if (null != degree) {
				g.rotate(Math.toRadians(degree));//设置水印旋转
			}
			JLabel label = new JLabel(waterMarkContent);
			FontMetrics metrics = label.getFontMetrics(font);
			int width = metrics.stringWidth(label.getText());//文字水印的宽
			int rowsNumber = srcImgHeight/width;// 图片的高  除以  文字水印的宽    ——> 打印的行数(以文字水印的宽为间隔)
			int columnsNumber = srcImgWidth/width;//图片的宽 除以 文字水印的宽   ——> 每行打印的列数(以文字水印的宽为间隔)
			//防止图片太小而文字水印太长，所以至少打印一次
			if(rowsNumber < 1){
				rowsNumber = 1;
			}
			if(columnsNumber < 1){
				columnsNumber = 1;
			}
			for(int j=0;j<rowsNumber;j++){
				for(int i=0;i<columnsNumber;i++){
					//g.drawString(waterMarkContent, i*width + j*width, -i*width + j*width);//画出水印,并设置水印位置  45度的时候使用
					g.drawString(waterMarkContent, -i*width + j*width, i*width + j*width);//画出水印,并设置水印位置
				}
			}

            g.dispose();
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent
     *            水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

	/*public static void main(String[] args) {
		waterMark("D:\\123.pdf",
				"D:\\PDFtestDemo.pdf", "清徐档案馆");

	}*/



//	public static void waterMarkA(String inputFile, String outputFile, String waterMarkName,BaseColor markBaseColor) {
//		try {
//			PdfReader reader = new PdfReader(inputFile);
//			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
//			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//			Rectangle pageRect = null;
//			PdfGState gs = new PdfGState();
////			gs.setFillOpacity(0.4f);
//			gs.setStrokeOpacity(0.6f);
//			int total = reader.getNumberOfPages() + 1;
//
//			JLabel label = new JLabel();
//			FontMetrics metrics;
//			int textH = 0;
//			int textW = 0;
//			label.setText(waterMarkName);
//			metrics = label.getFontMetrics(label.getFont());
//			textH = metrics.getHeight();
//			textW = metrics.stringWidth(label.getText());
//
//			PdfContentByte under;
//			for (int i = 1; i < total; i++) {
//				pageRect = reader.getPageSizeWithRotation(i);
//				under = stamper.getOverContent(i);
//				under.saveState();
//				under.setGState(gs);
//				under.beginText();
//				under.setFontAndSize(base, 20);
//				under.setColorFill(markBaseColor);
////				under.setColorFill(new BaseColor(192,192,192));
//				for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 14) {
//					for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 1) {
//						under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 60);
//					}
//				}
//				under.endText();
//			}
//
//			stamper.close();
//			reader.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

//	public static void optimize(String source, String target) {
//		Document doc = new Document(source);
//		//设置压缩属性
//		Document.OptimizationOptions opt = new Document.OptimizationOptions();
//		//删除PDF不必要的对象
//		opt.setRemoveUnusedObjects(true);
//		//链接重复流
//		opt.setLinkDuplcateStreams(false);
//		//删除未使用的流
//		opt.setRemoveUnusedStreams(false);
//		//删除不必要的字体
//		opt.setUnembedFonts(true);
//		//压缩PDF中的图片
//		opt.setCompressImages(true);
//		//图片压缩比， 0 到100可选，越低压缩比越大
//		opt.setImageQuality(10);
//		doc.optimizeResources(opt);
//		//优化web的PDF文档
//		doc.optimize();
//		doc.save(target);
//	}




    //public static void main(String[] args) {
//        // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
//    	 WaterMarkUtil.mark("d://a111.jpg", "d://aaa2.jpg",
//        		new Color(192,192,192), "清徐档案馆");
//    	 WaterMarkUtil.waterMarkOne("d://002.pdf", "d://a222_water.pdf", "一二三四五六七八九");
//    	 WaterMarkUtil.waterMark("d://a222.pdf", "d://a222_water.pdf", "清徐档案馆");

		/*WaterMarkUtil.waterMark("F:\\zjq\\a\\浙江省收件凭证.pdf",
				"F:\\zjq\\b\\浙江省收件凭证.pdf", "内蒙古气象局财务核算中心\n" +
						"\n" +
						"财务档案信息化系统",new BaseColor(192,192,192));*/
    //}





}
